package cn.nubia.admin.file.controller;

import cn.nubia.admin.application.apk.entity.ApkInfo;
import cn.nubia.admin.application.apk.utils.ApkUtil;
import cn.nubia.admin.application.apk.utils.IconUtil;
import cn.nubia.admin.application.bean.*;
import cn.nubia.admin.application.service.FirewareService;
import cn.nubia.admin.application.service.ScreenshotService;
import cn.nubia.admin.application.service.SoftItemService;
import cn.nubia.admin.application.service.SoftService;
import cn.nubia.admin.file.ImageTools;
import cn.nubia.admin.sysconfig.service.CategoryService;
import cn.nubia.admin.common.constant.PicSizeEnum;
import cn.nubia.admin.common.ftp.FtpClientUtil;
import cn.nubia.admin.common.springmvc.Response;
import cn.nubia.admin.common.utils.StringUtil;
import cn.nubia.admin.file.FileManager;
import cn.nubia.admin.file.bean.Upload;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by justin on 15/7/2.
 */
@Controller
@RequestMapping(value = "/admin/upload/")
public class FileUploadController {

    @Autowired
    SoftService softService;
    @Autowired
    ScreenshotService screenshotService;
    @Autowired
    FirewareService firewareService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    FtpClientUtil ftpClientUtil;
    @Autowired
    SoftItemService softItemService;
    /***
     * 上传APK处理
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "uploadApkFile",method = RequestMethod.POST)
    public Response<Upload> uploadApk(String inputName, HttpServletRequest request)throws IOException{
        if(StringUtil.isEmpty(inputName))return Response.getFailedResponse("上传出错，请重新上传",null);
        try{
            MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
            List<MultipartFile> files = fileRequest.getFiles(inputName);
            MultipartFile apkFile = files.get(0);
            String fileName = FileManager.getTimeStampFileName(apkFile.getOriginalFilename());
            String apkPath = FileManager.getLocalFile(FileManager.ABSPATH_APK,fileName);
            FileManager.uploadfiles(apkPath, apkFile);// 上传文件

            Upload upload = new Upload();
            upload.setFileUrl(FileManager.getAbsFile(apkPath));

            ApkInfo apkInfo = new ApkUtil().getApkInfo(apkPath);
            //处理初始化SOFT信息
            SoftVO softVO = upload.initApkInfo(apkInfo);
            softVO.setResolutionShow(softService.getResolutionShow(softVO.getResolution()));

            //根据ApkInfo中的packageName获取是否存在
            Soft soft = softService.getSoftByPackageName(apkInfo.getPackageName());
            if(soft != null){
                softVO.initFromSoftInfo(soft);
                //firewareName
                softVO.setMaxFirewareName(firewareService.getFirewareNameByFirewareSDK(softVO.getMaxFirewareId()));
                softVO.setMinFirewareName(firewareService.getFirewareNameByFirewareSDK(softVO.getMinFirewareId()));

                //category
                softVO.initCategory(categoryService.constructorCategory(softVO.getCategoryId()));
                upload.setSecondCatagories(categoryService.getSubCategoryList(softVO.getCategoryId()));
                if (softVO.getCategoryId2() != null && softVO.getCategoryId2()>0){
                    upload.setThirdCatagories(categoryService.getSubCategoryList(softVO.getCategoryId2()));
                }
                //是否已经上传
                SoftItem softItemDAO = softItemService.getByVersion(softVO.getSoftId(),softVO.getVersionCode());
                if(softItemDAO!=null){
                    upload.setExist(true);
                    softVO.setSoftItemId(softItemDAO.getId());
                }
            }


            //发布到ftp
            String absDir = FileManager.getAbsDir(apkPath);
            if(!ftpClientUtil.isDirExist(absDir))ftpClientUtil.createDirs(absDir);
            ftpClientUtil.addFile(absDir,fileName,new File(apkPath));
            FileUtils.forceDelete(new File(apkPath).getParentFile());
            return Response.getSuccessResponse(upload);
        } catch (Exception e){
            e.printStackTrace();
        }
        return Response.getFailedResponse("上传出错，请确认包完整性再上传",null);
    }

    /***
     * 上传客户端版本
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "uploadClientFile",method = RequestMethod.POST)
    public Response<Upload> UploadClient(String inputName, HttpServletRequest request){
        if(StringUtil.isEmpty(inputName))return Response.getFailedResponse("上传出错，请重新上传",null);
        MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
        List<MultipartFile> files = fileRequest.getFiles(inputName);
        MultipartFile apkFile = files.get(0);
        String fileName = FileManager.getTimeStampFileName(apkFile.getOriginalFilename());
        Upload upload = new Upload();
        String apkPath=FileManager.getLocalFile(FileManager.ABSPATH_APK, fileName);
        upload.setFileUrl(FileManager.getAbsFile(apkPath));
        try {
            FileManager.uploadfiles(apkPath, apkFile);// 上传文件
            //发布到ftp
            String absDir = FileManager.getAbsDir(apkPath);
            if(!ftpClientUtil.isDirExist(absDir))ftpClientUtil.createDirs(absDir);
            if(!ftpClientUtil.addFile(absDir, fileName, new File(apkPath))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            ApkInfo apkInfo = new ApkUtil().getApkInfo(apkPath);
            //处理icon
            upload.initIconPath();
            String asbIconDir = FileManager.getAbsDir(upload.getLocalIconUrl());
            if(!ftpClientUtil.isDirExist(asbIconDir))ftpClientUtil.createDirs(asbIconDir);

            IconUtil.extractFileFromApk(apkPath, apkInfo.getApplicationIcon(), upload.getLocalIconUrl());
            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_512.getSize(),PicSizeEnum.ICON_512.getSize()).toFile(upload.getLocalIcon512Url());

            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_125.getSize(), PicSizeEnum.ICON_125.getSize()).toFile(upload.getLocalIcon125Url());
            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_114.getSize(),PicSizeEnum.ICON_114.getSize()).toFile(upload.getLocalIcon114Url());
            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_114.getSize(),PicSizeEnum.ICON_114.getSize()).toFile(upload.getLocalIcon62Url());
            //上传图片到ftp
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIconUrl()),new File(upload.getLocalIconUrl()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon512Url()),new File(upload.getLocalIcon512Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon125Url()),new File(upload.getLocalIcon125Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon114Url()),new File(upload.getLocalIcon114Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon62Url()),new File(upload.getLocalIcon62Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            //初始化APK信息
            ClientVersion clientVersion = upload.getClientVersion().initApkInfo(apkInfo);
            clientVersion.setResolutionShow(softService.getResolutionShow(clientVersion.getResolution()));
            clientVersion.setMaxsdkName(firewareService.getFirewareNameByFirewareSDK(clientVersion.getMaxsdk()));
            clientVersion.setMinsdkName(firewareService.getFirewareNameByFirewareSDK(clientVersion.getMinsdk()));

            FileUtils.forceDelete(new File(apkPath).getParentFile());
            FileUtils.forceDelete(new File(upload.getLocalIconUrl()).getParentFile());
            return Response.getSuccessResponse(upload);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.getFailedResponse("上传出错，请确认包完整性再上传",null);
    }

    /****
     * 上传应用ICON
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "uploadIconFile",method = RequestMethod.POST)
    public Response<Upload> uploadIconFile(String inputName, HttpServletRequest request)throws IOException{
        if(StringUtil.isEmpty(inputName))return Response.getFailedResponse("上传出错，请重新上传",null);
        try{
            MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
            List<MultipartFile> files = fileRequest.getFiles(inputName);
            MultipartFile iconFile = files.get(0);
            Upload upload = new Upload();
            upload.initIconPath();
            String asbIconDir = FileManager.getAbsDir(upload.getLocalIconUrl());
            if(!ftpClientUtil.isDirExist(asbIconDir))ftpClientUtil.createDirs(asbIconDir);
            FileManager.uploadfiles(upload.getLocalIconUrl(), iconFile);// 上传文件
            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_512.getSize(),PicSizeEnum.ICON_512.getSize()).toFile(upload.getLocalIcon512Url());
            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_125.getSize(),PicSizeEnum.ICON_125.getSize()).toFile(upload.getLocalIcon125Url());
            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_114.getSize(),PicSizeEnum.ICON_114.getSize()).toFile(upload.getLocalIcon114Url());
            Thumbnails.of(upload.getLocalIconUrl()).forceSize(PicSizeEnum.ICON_62.getSize(),PicSizeEnum.ICON_62.getSize()).toFile(upload.getLocalIcon62Url());
            //上传图片到ftp
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIconUrl()),new File(upload.getLocalIconUrl()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon512Url()),new File(upload.getLocalIcon512Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon125Url()),new File(upload.getLocalIcon125Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon114Url()),new File(upload.getLocalIcon114Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbIconDir,FileManager.getFileName(upload.getLocalIcon62Url()),new File(upload.getLocalIcon62Url()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            FileUtils.forceDelete(new File(upload.getLocalIconUrl()).getParentFile());
            return Response.getSuccessResponse(upload);
        } catch (Exception e){
            e.printStackTrace();
        }
        return Response.getFailedResponse("上传出错，请重新上传", null);
    }

    /****
     * 上传应用的广告图
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "uploadAdFile",method = RequestMethod.POST)
    public Response<Upload> uploadAdFile(String inputName,  HttpServletRequest request)throws IOException{
        if(StringUtil.isEmpty(inputName))return Response.getFailedResponse("上传出错，请重新上传",null);
        try{
            MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
            List<MultipartFile> files = fileRequest.getFiles(inputName);
            MultipartFile adFile = files.get(0);
            Upload upload = new Upload();
            upload.initADPath();
            String asbAdDir = FileManager.getAbsDir(upload.getLocalAdUrl());
            if(!ftpClientUtil.isDirExist(asbAdDir))ftpClientUtil.createDirs(asbAdDir);
            FileManager.uploadfiles(upload.getLocalAdUrl(), adFile);// 上传文件
            Thumbnails.of(upload.getLocalAdUrl()).width(PicSizeEnum.AD_THUMBS.getSize()).toFile(upload.getLocalAdThumbUrl());
            if(!ftpClientUtil.addFile(asbAdDir,FileManager.getFileName(upload.getLocalAdUrl()),new File(upload.getLocalAdUrl()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            if(!ftpClientUtil.addFile(asbAdDir,FileManager.getFileName(upload.getLocalAdThumbUrl()),new File(upload.getLocalAdThumbUrl()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            FileUtils.forceDelete(new File(upload.getLocalAdUrl()).getParentFile());

            return Response.getSuccessResponse(upload);
        } catch (Exception e){
            e.printStackTrace();
        }
        return Response.getFailedResponse("上传出错，请重新上传",null);
    }

    /****
     * 上传应用的广告图
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "uploadScreenShot",method = RequestMethod.POST)
    public Response<ScreenShot> uploadScreenShot(String inputName, HttpServletRequest request)throws IOException{
        if(StringUtil.isEmpty(inputName))return Response.getFailedResponse("上传出错，请重新上传",null);
        try{
            MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
            List<MultipartFile> files = fileRequest.getFiles(inputName);
            MultipartFile screenshotFile = files.get(0);
            ScreenShot screenShot = new ScreenShot();
            screenShot.setScreenName(FileManager.getTimeStampFileName(screenshotFile.getOriginalFilename()));
            screenShot.setScreenSize((int) screenshotFile.getSize());
            screenShot.initScreenshotPath();
            FileManager.uploadfiles(screenShot.getLocalScreenshotUrl(), screenshotFile);// 上传文件
            String asbScreenShotDir = FileManager.getAbsDir(screenShot.getLocalScreenshotUrl());
            if(!ftpClientUtil.isDirExist(asbScreenShotDir))ftpClientUtil.createDirs(asbScreenShotDir);
            if(!ftpClientUtil.addFile(asbScreenShotDir, FileManager.getFileName(screenShot.getLocalScreenshotUrl()), new File(screenShot.getLocalScreenshotUrl()))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            screenshotService.insertScreen(screenShot);
            FileUtils.forceDelete(new File(FileManager.getLocalPath(asbScreenShotDir)).getParentFile());
            return Response.getSuccessResponse(screenShot);
        } catch (Exception e){
            e.printStackTrace();
        }
        return Response.getFailedResponse("上传出错，请重新上传",null);
    }

    /***
     * 分类ICON上传
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "uploadPic",method = RequestMethod.POST)
    public Response<String> uploadPic(String inputName, HttpServletRequest request)throws IOException{
        if(StringUtil.isEmpty(inputName))return Response.getFailedResponse("上传出错，请重新上传",null);
        try{
            MultipartHttpServletRequest fileRequest = (MultipartHttpServletRequest)request;
            List<MultipartFile> files = fileRequest.getFiles(inputName);
            MultipartFile screenshotFile = files.get(0);
            InputStream is = null;
            try {
                is = screenshotFile.getInputStream();
                int[] ret = ImageTools.getImgWidthHeight(is);//ret[0] 宽 ret[1] 高
                if (ret[0] != 512 && ret[1] != 512) {
                    return Response.getFailedResponse("请上传512*512像素的png图片",null);
                }
            }catch (Exception e){
                e.printStackTrace();
                return  Response.getFailedResponse("上传出错，请重新上传",e.getMessage()+e.toString());
            }
            finally {
                if (is != null){
                    is.close();
                }
            }


            String filename = FileManager.getTimeStampFileName(screenshotFile.getOriginalFilename());
            String picLocalFileName = FileManager.getLocalFile(FileManager.ABSPATH_PIC,filename);
            FileManager.uploadfiles(picLocalFileName, screenshotFile);// 上传文件
            String asbPicFileDir = FileManager.getAbsDir(picLocalFileName);
            if(!ftpClientUtil.isDirExist(asbPicFileDir))ftpClientUtil.createDirs(asbPicFileDir);
            if(!ftpClientUtil.addFile(asbPicFileDir, FileManager.getFileName(picLocalFileName), new File(picLocalFileName))){
                return Response.getFailedResponse("上传出错，请重新上传",null);
            }
            FileUtils.forceDelete(new File(picLocalFileName).getParentFile());
            String absPicPath =FileManager.getAbsFile(picLocalFileName);
            return Response.getSuccessResponse(absPicPath);
        } catch (Exception e){
            e.printStackTrace();
            return  Response.getFailedResponse("上传出错，请重新上传",e.getMessage()+e.toString());
        }
    }

    /**
     * 下载
     * @param path
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "download")
    public ResponseEntity<byte[]> download(String path) throws IOException {
        File file=new File(FileManager.getLocalPath(path));
        String filePath = FileManager.getAbsDir(FileManager.getLocalPath(path));
        file = ftpClientUtil.getFile(filePath,FileManager.getFileName(path),file);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", FileManager.getFileName(path));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
        FileUtils.forceDelete(file.getParentFile());
        return responseEntity;
    }
}
